package com.example.administrator.fangbook.importlocal.utils;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.example.administrator.fangbook.importlocal.bean.FileNode;
import com.example.administrator.fangbook.utils.LogUtil;

import java.io.File;
import java.io.FileFilter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ScanSdUtil extends HandlerThread {
    private static final int SCAN_SUB_FILES = 0x1001;
    private static final int SCAN_BOOK_FILES = 0x1002;
    private ScanSucceedLisener lisener;
    private RunFlag mRunFlag;
    private Handler mMainHandler;
    private ScanHandler mScanHandler;

    public ScanSdUtil(ScanSucceedLisener lisener) {
        super("FileScanHelper_Thread", Thread.NORM_PRIORITY);
        mRunFlag = RunFlag.NOT_START;
        this.lisener = lisener;
    }

    public void scanFiles(FileNode fileNode) {
        if (RunFlag.NOT_START == mRunFlag) {
            startWork();
        }
        //发送消息到子线程开始工作
        Message msg = Message.obtain(mScanHandler);
        msg.what = SCAN_BOOK_FILES;
        msg.obj = fileNode;
        mScanHandler.sendMessage(msg);
    }

    private void startWork() {
        if (RunFlag.NOT_START.equals(mRunFlag)) {
            mRunFlag = RunFlag.RUNNING;
            start();
            mScanHandler = new ScanHandler(this, this.getLooper());
            mMainHandler = new Handler(Looper.getMainLooper());
        }
    }

    public void stopWork() {
        LogUtil.e("线程","ScanSdUtil--stopWork");
        mRunFlag = RunFlag.STOPPED;
        mMainHandler.removeCallbacksAndMessages(null);
        mMainHandler = null;
        mScanHandler.removeCallbacksAndMessages(null);
        mScanHandler = null;
        quit();
    }


    static class ScanHandler extends Handler {
        private WeakReference<ScanSdUtil> mOut;

        public ScanHandler(ScanSdUtil out, Looper looper) {
            super(looper);
            mOut = new WeakReference<ScanSdUtil>(out);
        }

        @Override
        public void handleMessage(Message msg) {
            ScanSdUtil out = mOut.get();
            if (out == null) {
                return;
            }
            switch (msg.what) {
                case SCAN_BOOK_FILES:
                    if (msg.obj != null) {
                        out.doScanFiles((FileNode) msg.obj);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 子线程中开始扫描
     *
     * @param node
     */
    private void doScanFiles(FileNode node) {
        if (!RunFlag.RUNNING.equals(mRunFlag)) {
            return;
        }
        final List<FileNode> results = new ArrayList<FileNode>();
        File file = node.getFile();
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                boolean ret = file.isDirectory();
                String fileName = file.getPath().toLowerCase();
                ret = ret || fileName.endsWith(".txt") || fileName.endsWith(".epub") || fileName.endsWith(".zb");
                return ret;
            }
        });
        if (!RunFlag.RUNNING.equals(mRunFlag)) {
            return;
        }

        if (files != null) {
            FileNode tmp;
            for (int i = 0; i < files.length; i++) {
                if (!RunFlag.RUNNING.equals(mRunFlag)) {
                    return;
                }
                tmp = new FileNode(node, files[i]);
                //判断是否是目录
                if (tmp.isDirectory()) {
                    //继续递归调用
                    scanFiles(tmp);
                } else {
                    if (FileType.CHINESE_ALL.equals(tmp.getType())) {
                        //中文书城的图书
//                        ShelfItemBook book = BookshelfManager.getInstance().getBookInfoFromFile(tmp.getFile());
//                        if (book != null) {
//                            tmp.setFullName(book.getName());
//                            tmp.setPath(book.getBookId());
//                            tmp.setAuthor(book.getAuthorName());
//                            tmp.createFirstPinYinChar();
//                            results.add(tmp);
//                        }
                    } else {
                        tmp.createFirstPinYinChar();
                        results.add(tmp);
                    }
                }
                tmp = null;
            }
        }
        if (!RunFlag.RUNNING.equals(mRunFlag)) {
            return;
        }
        if (!results.isEmpty()) {
            fireScanResults(results, node);
        }
    }

    private void fireScanResults(final List<FileNode> results, final FileNode currNode) {
        if (mMainHandler != null) {
            mMainHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (!RunFlag.RUNNING.equals(mRunFlag)) {
                        return;
                    }
                    lisener.scanSucceed(results, currNode);
                }
            });
        }
    }


    private enum RunFlag {
        /**
         * 线程没有start
         */
        NOT_START,
        /**
         * 线程已经开始运行
         */
        RUNNING,
        /**
         * 已经停止运行
         */
        STOPPED
    }

    public interface ScanSucceedLisener {
        public void scanSucceed(List<FileNode> results, FileNode currNode);
    }
}
